package org.example.finalsecurities.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.finalsecurities.entity.ChangeInfo;
import org.example.finalsecurities.entity.CrawlerLog;
import org.example.finalsecurities.entity.FlowInfo;
import org.example.finalsecurities.mapper.FlowInfoMapper;
import org.example.finalsecurities.service.CrawlerLogService;
import org.example.finalsecurities.service.FlowInfoService;
import org.example.finalsecurities.utils.CrawlerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author 戴诚棋
 * @version 1.0
 */
@Service
@Slf4j
public class FlowInfoServiceImpl implements FlowInfoService {
    @Autowired
    private FlowInfoMapper flowInfoMapper;
    @Autowired
    private CrawlerLogService crawlerLogService;

    @Override
    public void insertFlowInfo() {
        Integer id = 1;
        Date startTime = new Date();
        log.info("开始爬取股票数据: {}", startTime);

        // 构建请求参数
        CrawlerLog crawlerLog = new CrawlerLog();
        crawlerLog.setActionDesc("爬取港股通资金流");
        crawlerLog.setUrl("https://data.eastmoney.com/hsgt/hsgtV2.html");
        crawlerLog.setStartTime(startTime);
        //爬取港股通资金流数据
        List<FlowInfo> flowInfos = CrawlerUtil.crawlFlowInfo();
        // 保存爬取日志
        Date endTime = new Date();

        crawlerLog.setEndTime(endTime);
        crawlerLog.setCreateTime(endTime);
        crawlerLog.setUpdateTime(endTime);

        crawlerLogService.saveLog(crawlerLog);
        log.info("爬取股票数据完成，本次爬虫日志: {}", crawlerLog);
//        System.out.println(flowInfos.toString());
        if (flowInfos != null) {
            for (FlowInfo flowInfo : flowInfos) {
                flowInfo.setId(id++);
                flowInfo.setCreateTime(new Date());
                flowInfo.setUpdateTime(new Date());
            }
        }
        //先判断表中是否存在数据
        List<FlowInfo> flowInfoList = getFlowInfoList();
        //如果表中没有数据,插入数据
        if (flowInfoList.isEmpty()) {
            //将数据插入
            flowInfoMapper.insert(flowInfos);
        }else {
            //更新数据
            flowInfoMapper.update(flowInfos);
        }
    }

    /**
     *
     * @return 查询到的数据列表
     * 查询数据库中对应表的信息
     */
    @Override
    public List<FlowInfo> getFlowInfoList() {
        List<FlowInfo> flowInfoList = flowInfoMapper.selectAll();
        return flowInfoList;
    }
}
